<?php


namespace app\admin\controller\chao;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="变更订单列表")
 */
class ChangeOrder extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Order();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
           
            list($page, $limit, $where) = $this->buildTableParames();

            $where = [];
            //状态（1待审核，2审核通过，3驳回）
            if(!empty($param['change_status']) && isset($param['change_status']))
            {
                $where[] = [
                    ['change_status', '=', $param['change_status']],
                ];
            }else{
                $where[] = [
                    ['change_status', 'in', [1,2,3]],
                ];
            }

            $session = session("admin");
            $type = $session["type"];//类型（0超管，1业务员，2仓库员）
            if($type == 0){
                if(!empty($param['order_no']) && isset($param['order_no']))
                {
                    $where[] = [
                        ['order_no', '=', $param['order_no']],
                    ];
                }
                  
                //收货人
                if(!empty($param['consignee']) && isset($param['consignee']))
                {
                    $where[] = [
                        ['consignee', '=', $param['consignee']],
                    ];
                }
                //负责人
                if(!empty($param['kahuna_name']) && isset($param['kahuna_name']))
                {
                    $where[] = [
                        ['kahuna_name', '=', $param['kahuna_name']],
                    ];
                }
                $count = $this->model
                ->where($where)
                ->where("is_change",2)
                ->where("delete_time",Null)
                ->count();
                $list = $this->model
                    ->where("is_change",2)
                    ->where("delete_time",Null)
                    ->where($where)
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
                foreach ($list as $k => $v){
                    //admin_type  用户类型
                    $session = session("admin");
                    $v["admin_type"] = $session["type"];
                    $v["change_application_time"] = date("Y-m-d H:i:s",$v["change_application_time"]);
                    $admin = Db::name("system_admin")->where("id",$v["kahuna_id"])->find();
                    if(!empty($admin["employee_name"])){
                        $v["employee_name"] = $admin["employee_name"];
                    }else{
                        $v["employee_name"] = "";
                    }
                    $list[$k] = $v;
                }
            }elseif($type == 1){
                if(!empty($param['order_no']) && isset($param['order_no']))
                {
                    $where[] = [
                        ['order_no', '=', $param['order_no']],
                    ];
                }
                  
                //收货人
                if(!empty($param['consignee']) && isset($param['consignee']))
                {
                    $where[] = [
                        ['consignee', '=', $param['consignee']],
                    ];
                }
                //联系电话
                if(!empty($param['contact_phone']) && isset($param['contact_phone']))
                {
                    $where[] = [
                        ['contact_phone', '=', $param['contact_phone']],
                    ];
                }
                $count = $this->model
                ->where($where)
                ->where("is_change",2)
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $list = $this->model
                    ->where("is_change",2)
                    ->where("delete_time",Null)
                    ->where("kahuna_id",$session["id"])
                    ->where($where)
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
                foreach ($list as $k => $v){
                    //admin_type  用户类型
                    $session = session("admin");
                    $v["admin_type"] = $session["type"];
                    $v["change_application_time"] = date("Y-m-d H:i:s",$v["change_application_time"]);
                    $admin = Db::name("system_admin")->where("id",$v["kahuna_id"])->find();
                    if(!empty($admin["employee_name"])){
                        $v["employee_name"] = $admin["employee_name"];
                    }else{
                        $v["employee_name"] = "";
                    }
                    $list[$k] = $v;
                }
            }elseif($type == 2){
                if(!empty($param['order_no']) && isset($param['order_no']))
                {
                    $where[] = [
                        ['order_no', '=', $param['order_no']],
                    ];
                }
                  
                //收货人
                if(!empty($param['consignee']) && isset($param['consignee']))
                {
                    $where[] = [
                        ['consignee', '=', $param['consignee']],
                    ];
                }
            }
       
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    //变更订单通过
    public function change_order_review(){
        if ($this->request->isAjax()) {
            $session = session("admin");
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('change_status', 1)->find();
            if (empty($ret)) {
                $cflsg = $this->model->where('id', $post['id'])->where('status', 6)->find();
                //查看订单商品是否出库，如果出库的话，就得作废入库    判断订单状态是否为6  6位已出库
                if(!empty($cflsg)){
                    //订单商品作废入库
                    $order_item = Db::name("order_item")->where("oid",$post["id"])->field("gid,good_name,num")
                                ->paginate()->each(function($item){
                                    $goods = Db::name("goods")->where("id",$item["gid"])->find();
                                    $good_type = Db::name("good_type")->where("id",$goods["good_type_id"])->find();
                                    $item["good_type_id"] = $good_type["id"];
                                    $item["good_type_name"] = $good_type["title"];
                                    $item["good_bar_code"] = $goods["bar_code"];
                                    return $item;
                                });
                    $order_item = $order_item->toArray();
                    $goodsw_item = $order_item["data"];
                
                    //入库单号
                    $receipt_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$session['id'];
        
                    $data_zf = [
                        "receipt_no"=>$receipt_no,
                        "receipt_name"=>"系统作废订单商品入库",
                        "status"=>2,
                        "receipt_type"=>2,
                        "warehousing_time"=>date("Y-m-d H:i:s",time()),
                        "receipt_username"=>$session["employee_name"],//入库人姓名
                        "receipt_id"=>$session["id"],//入库人id
                    ];
                    Db::name("goods_warehousing")->insert($data_zf);
                    $goodsw_id = Db::name('goods_warehousing')->getLastInsID();
                    //添加入库商品信息 
                    foreach($goodsw_item as $k=>$v){
                        $v["goods_warehousing_id"] = $goodsw_id;
                        $goodsw_item[$k] = $v;
                    }
                    Db::name('goods_warehousing_item')->insertAll($goodsw_item); 
                    $admin = Db::name("system_admin")->where("id",$session["id"])->find();
                    $adminarr = Db::name("system_admin")->where("id",$cflsg["kahuna_id"])->find();
                    foreach($goodsw_item as $k=>$ve){
                        //添加出入库明细
                        $data_crk = [
                            "data_id"=>$goodsw_id,//数据id
                            'odd_numbers'=>$receipt_no,//单号
                            "gid"=>$ve["gid"],
                            "good_type_id"=>$ve["good_type_id"],
                            "good_type_name"=>$ve["good_type_name"],
                            "receipt_issue_type"=>2,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                            "create_time"=>time(),
                            "receipt_issue_num"=>$ve["num"], //出入库数量
                            "tracking_numbercr"=>$cflsg["courier_number"],
                            "discrepancy"=>$admin["employee_name"],//出入库员
                            "order_head"=>$adminarr["employee_name"]//负责人
                        ];
                        Db::name("receipt_issue_detailed")->insert($data_crk);
                        //修改商品库存
                        Db::name("goods")->where("id",$ve["gid"])->inc("stock",$ve["num"])->update();
                        Db::name("goods")->where("id",$ve["gid"])->dec("sales_volume",$ve["num"])->update();
                        //出库订单变更状态
                        $this->model->where('id', $post['id'])->update(["status"=>8]);
                        //添加未读消息提示
                        Db::name("message_prompt")->insert([
                            "oid"=>$post['id'],
                            "type"=>3
                        ]);
                    }
                    $this->success('操作成功', '');
                }else{
                    $this->error('此订单不能作废', '');
                }
            }
            $admin = Db::name("system_admin")->where("id",$session["id"])->find();
            if(!empty($admin["employee_name"])){
                $employee_name = $admin["employee_name"];
            }else{
                $employee_name = "";
            }
            //$this->model->where('id', $post['id'])->update(["change_status"=>2,"is_edit"=>2,"change_auditor"=>$session["username"],"change_auditor_id"=>$session["id"]]);
            //变更审核通过
            if($ret["status"] == 3){
                $this->model->where('id', $post['id'])->update(["change_status"=>2,"status"=>1,"change_auditor"=>$employee_name,"change_auditor_id"=>$session["id"]]);
            }elseif($ret["status"] == 5 && $ret["is_cooperate"] == 1){
                $this->model->where('id', $post['id'])->update(["change_status"=>2,"status"=>1,"change_auditor"=>$employee_name,"change_auditor_id"=>$session["id"]]);
            }elseif($ret["status"] == 10){
                if(empty($post["noodle_image"])){
                    $this->error('快递面单图片不能为空', '');
                }
                $this->model->where('id', $post['id'])->update(["courier_number"=>"","noodle_image"=>$post["noodle_image"],"change_status"=>2,"status"=>1,"change_auditor"=>$employee_name,"change_auditor_id"=>$session["id"]]);
            }elseif($ret["status"] == 5 && $ret["is_cooperate"] == 2){
                if(empty($post["noodle_image"])){
                    $this->error('快递面单图片不能为空', '');
                }
                Db::name("order")->where('id', $post['id'])->update(["courier_number"=>"","noodle_image"=>$post["noodle_image"],"change_status"=>2,"status"=>1,"change_auditor"=>$employee_name,"change_auditor_id"=>$session["id"]]);
            }
            //type 1新订单  2变更单  3作废单   变更消息关闭
            Db::name("message_prompt")->where("oid",$post["id"])->where("type",2)->update(["status"=>2]);
            $this->success('操作成功', '');
        }
    }

    //变更订单驳回
    public function change_order_refuse(){
        if ($this->request->isAjax()) {
            $session = session("admin");
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('change_status', 1)->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能驳回');
            }
            if(empty($post['change_reason'])){
                $this->error('驳回原因不能为空');
            }
            $admin = Db::name("system_admin")->where("id",$session["id"])->find();
            if(!empty($admin["employee_name"])){
                $employee_name = $admin["employee_name"];
            }else{
                $employee_name = "";
            }
            $this->model->where('id', $post['id'])->update([
                "change_reason"=>$post["change_reason"],
                "change_status"=>3,
                "change_auditor"=>$employee_name,
                "change_auditor_id"=>$session["id"]
            ]);
            //type 1新订单  2变更单  3作废单   变更消息关闭
            Db::name("message_prompt")->where("oid",$post["id"])->where("type",2)->update(["status"=>2]);
            $this->success('变更驳回成功', '');
        }
    }

    //变更订单未完结上传图片
    public function unfinished_img(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['image'])){
                $this->error('图片不能为空');
            }
            $this->model->where('id', $post['id'])->update([
                "void_picture"=>$post["image"],
                "void_characters"=>$post["void_characters"]
            ]);
            $this->success('上传成功');
        }
    }

    //手动点击变更单完结
    public function chaorder_end(){
        if ($this->request->isAjax()) {
            $session = session("admin");
            $post = $this->request->param();
            //->where('change_status', 0)
            $ret = $this->model->where('id', $post['id'])->where('status', 8)->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能完结');
            }
            $admin = Db::name("system_admin")->where("id",$session["id"])->find();
            if(!empty($admin["employee_name"])){
                $employee_name = $admin["employee_name"];
            }else{
                $employee_name = "";
            }
            $this->model->where('id', $post['id'])->update([
                "status"=>9,
                "completed_by"=>$employee_name,
                "completed_time"=>time(),
            ]);
            $this->success('操作成功');
        }
    }
    






    
 
} 